package yxy.game.pm2.module.tower;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import org.redisson.api.RMap;
import yxy.cherry.battle.module.Position;
import yxy.cherry.battle.module.record.FighterPosition;
import yxy.cherry.battle.module.record.FighterSide;
import yxy.cherry.battle.module.record.result.BattleResult;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.herodata;
import yxy.cherry.data.bean.tower;
import yxy.cherry.data.bean.towerlvreward;
import yxy.cherry.data.script.fomula;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.cherry.game.base.redis.RedisType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Format.FormatType;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.message.BattleMessage;
import yxy.game.pm2.message.BattleMessage.BattleExecuteResponse;
import yxy.game.pm2.message.TowerMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.battle.*;
import yxy.game.pm2.module.stat.StatHandle;
import yxy.game.pm2.module.task.TaskHandle;

/**
 * 爬塔
 */
public class TowerHandle extends BattleModuleHandle {

    final public static int battleExpireDay = 1;// 战斗数据过期时间（天）

    protected String code() {
        return BattleType.TOWER.name();
    }

    public BattleMessage.BattleResponse battleResponse(String playerCode, int floor, boolean first) throws Exception {
        BattleHandle battleHandle = new BattleHandle();

        BattleModule battleModule = createBattleModule(playerCode, floor, first);

        return battleHandle.battleResponse(battleModule);
    }

    public BattleExecuteResponse battleResponseExecute(String playerCode, BattleMessage.BattleExecuteRequest request) throws Exception {
        BattleModule battleModule = BattleModule.get(playerCode, code());
        int floor = ((SettlementTower) battleModule.getSettlement()).getFloor();
        TowerModule towerModule = TowerModule.get(playerCode);
        try {
            if (towerModule.tryLock()) {
                if (floor <= towerModule.getFloor()) {
                    // 旧关卡
                    towerModule.setTimes(towerModule.getTimes() + 1);
                    towerModule.set();
                }

                int[] angersTeamA = null;
                if (request != null) {
                    List<BattleMessage.FighterInfo> fighterInfos = request.getFormatList();
                    ArrayList<BattleMessage.FighterInfo> fighterInfosTeamA = new ArrayList<>();
                    for (BattleMessage.FighterInfo fighterInfo : fighterInfos) {
                        FighterPosition fp = FighterPosition.forNumber(fighterInfo.getPosition().getNumber());
                        if (fp.getSide().equals(FighterSide.LEFT)) {
                            fighterInfosTeamA.add(fighterInfo);
                        }
                    }
                    angersTeamA = new BattleHandle().angersFromFormatList(fighterInfosTeamA);
                }
                towerModule.setAngers(angersTeamA);
                towerModule.set();
            }
        } catch (Exception e) {
        } finally {
            towerModule.unlock();
        }
        BattleExecuteResponse response = new BattleHandle().battleResponseExecute(battleModule, towerModule.getAngers(), null);

        // 判断塔层记录
        if (battleModule.getBattleResult().equals(BattleResult.LEFT_WIN)) {
            TowerFloorModule floorModule = TowerFloorModule.get(playerCode, floor);
            if (floorModule != null) {
                floorModule.record(playerCode, battleModule);
                TaskHandle.handle(playerCode, TaskType.统计型_修炼塔_挑战_次数, 1);
            }
        }

        return response;
    }

    //修炼塔跳转某关并生成战斗记录
    public BattleExecuteResponse battleSkipTowerResponseExecute(String playerCode, TowerModule towerModule) throws Exception {
        BattleModule battleModule = BattleModule.get(playerCode, code());
        BattleExecuteResponse response = new BattleHandle().battleResponseExecute(battleModule, towerModule.getAngers(), null);
        return response;
    }


    public BattleExecuteResponse battleResponseExecuteQuick(String playerCode, int floor, boolean first) {
        TowerModule towerModule = TowerModule.get(playerCode);

        BattleModule battleModule = createBattleModule(playerCode, floor, first);

        BattleExecuteResponse response = new BattleHandle().battleResponseExecute(battleModule, towerModule.getAngers(), null);

        // 判断塔层记录
        if (battleModule.getBattleResult().equals(BattleResult.LEFT_WIN)) {
            TowerFloorModule floorModule = TowerFloorModule.get(playerCode, floor);
            if (floorModule != null) {
                floorModule.record(playerCode, battleModule);
                TaskHandle.handle(playerCode, TaskType.统计型_修炼塔_挑战_次数, 1);
            }
        }

        return response;
    }

    private BattleModule createBattleModule(String playerCode, int floor, boolean first) {
        BattleHandle battleHandle = new BattleHandle();

        BattleModule battleModule = BattleModule.create(playerCode);
        battleModule.setType(BattleType.TOWER);
        battleModule.setCode(code());

        // 玩家的team
        TeamModule teamA = battleHandle.teamPlayer(playerCode, FormatType.普通);
        battleModule.setTeamA(teamA);

        // 征战地图
        TeamModule teamB = teamTower(floor);
        battleModule.setTeamB(teamB);

        battleModule.setSettlement(SettlementTower.create(playerCode, floor, first));

//        PlayerBean playerBean = PlayerBean.get(playerCode);
//        int skipLevel = fomula.速战功能等级条件.intValue();
//        int skipVip = fomula.速战功能VIP条件.intValue();
//        battleModule.setSkip(playerBean.getViplevel() >= skipVip || playerBean.getLevel() >= skipLevel);

        battleModule.set(battleExpireDay);

        return battleModule;
    }

    public TeamModule teamTower(int floor) {
        TeamModule team = new TeamModule();
        tower _towerdata = DataCenter.getData(floor, tower.class);

        ArrayList<FighterModule> fighterModules = getFighterModuleList(floor);

        //战力
        long totalPower = 0;

        // 武将
        for (int i = 0; i < _towerdata.getHeroid().length; i++) {
            Position position = Position.forValue(i + 1);
            int heroid = _towerdata.getHeroid()[i];
            if (heroid == -1) continue;
            FighterModule fighterModule = fighterModules.get(i);
            team.addfighter(position, fighterModule);
            totalPower +=fighterModule.getTotalPower();
        }
        // 神器
        WeaponModule weapon = WeaponModule.create(_towerdata.getWeapondataid(), _towerdata.getWeaponlv(), 0, 0, _towerdata.getWeaponskilllv());
        team.setWeapon(weapon);

        // 信息
        herodata _herodata = DataCenter.getData(_towerdata.getMain(), herodata.class);
        team.setName(_herodata.getName());
        team.setHead(_towerdata.getHeadid());
        team.setPower(totalPower);

        return team;
    }

    public Boolean nextFloor(String playerCode, int battlefloor) {
        TowerModule module = TowerModule.get(playerCode);
        try {
            if (module.tryLock()) {
                boolean newfloor = battlefloor > module.getFloor();
                if (!newfloor) {
                    return false;
                }
                if (DataCenter.getData(battlefloor, tower.class) != null) {
                    module.setFloor(battlefloor);

                    // 记录排行榜
                    RankTower.getRank(playerCode).put(playerCode, battlefloor);

                    StatHandle.stat_关卡统计(playerCode, CCReason.修炼塔, battlefloor);
                }

                module.set();
            }
        } catch (Exception e) {
            return false;
        } finally {
            module.unlock();
        }
        return true;
    }

    /**
     * 爬塔关卡奖励
     */
    public Result levelReward(String playerCode, int id, TowerMessage.TowerBonusReceiveResponse.Builder response) {
        TowerModule module = TowerModule.get(playerCode);
        try {
            if (module.tryLock()) {
                for (int i = 0, size = module.getLevelReward().size(); i < size; i++) {
                    int levelRewardId = module.getLevelReward().get(i);
                    if (levelRewardId == id) {
                        return Result.TowerBonusRewarded;// 这个奖励已经领过
                    }
                }

                towerlvreward _levelreward = DataCenter.getData(id, towerlvreward.class);
                Collection<Currency> rewards = Currency.create(_levelreward.getRewardtype(), _levelreward.getRewardid(), _levelreward.getRewardnum());
                new CurrencyHandle().addCurrency(playerCode, CCReason.修炼塔, rewards);

                response.addAllRewards(new CurrencyHandle().packItems(rewards));
                module.getLevelReward().add(_levelreward.getId());
                module.set();

                for (Integer levelRewardId : module.getLevelReward()) {
                    response.addBox(levelRewardId);
                }

                return Result.Success;
            }
        } catch (Exception e) {
        } finally {
            module.unlock();
        }
        return Result.DataError;
    }

    public static Collection<Currency> floorRewards(int floor, boolean first) {
        ArrayList<Currency> rewards = new ArrayList<>();
        tower towerdata = DataCenter.getData(floor, tower.class);
        if (towerdata == null) {
            return rewards;
        }
        rewards.addAll(Currency.create(towerdata.getRewardtype(), towerdata.getRewardid(), towerdata.getRewardnum()));
        if (first) {
            rewards.addAll(Currency.create(towerdata.getFirsttype(), towerdata.getFirstid(), towerdata.getFirstnum()));
        }
        return rewards;
    }

//	public static int maxtimes() {
//		return fomula.修炼塔每日挑战次数.intValue();
////		return 300;
//	}

//	public static int maxbuytimes() {
//		return fomula.修炼塔每日购买次数.intValue();
//	}

    public static int buytimescost(int buytimes) {
        return fomula.修炼塔购买次数花费元宝数.intValue(buytimes);
    }

    /**
     * 封装层消息
     */
    public void packTowerFloor(String playerCode, int floor, TowerMessage.TowerFloorResponse.Builder response) {
        TowerFloorModule floorModule = TowerFloorModule.get(playerCode, floor);
        if (floorModule == null) {
            return;
        }
        try {
            response.setBestTime(packTowerFloorBest(floorModule.getBestRound()));
        } catch (Exception e) {
        }
        try {
            response.setBestPower(packTowerFloorBest(floorModule.getBestPower()));
        } catch (Exception e) {
        }
    }

    private TowerMessage.TowerFloorBest packTowerFloorBest(TowerFloorRecord bestRecord) {
        PlayerBean playerBean = PlayerBean.get(bestRecord.getPlayerCode());
        TowerMessage.TowerFloorBest.Builder builder = TowerMessage.TowerFloorBest.newBuilder();
        builder.setPlayerCode(playerBean.getCode());
        builder.setNickname(playerBean.getName());
        builder.setHead(playerBean.getHead());
        builder.setHeadFrame(playerBean.getHeadframe());

        builder.setBattleCode(bestRecord.getRecordCode());
        builder.setValue(bestRecord.getValue());
        return builder.build();
    }


    //获取内存怪物战力属性
    public ArrayList<FighterModule> getFighterModuleList(int floor){
        RMap<String, ArrayList<FighterModule>> rMap = RedisManager.getInstance().getConnection(RedisType.REDIS_DATA).client().getMap("INIT:tower");
        JSONArray arrary = (JSONArray) JSONArray.toJSON(rMap.get(String.valueOf(floor)));
        ArrayList<FighterModule> fighterModules = JSON.parseObject(arrary.toString(), new TypeReference<ArrayList<FighterModule>>() {
        });
        return fighterModules;
    }

}
